<template>
<div :class="[$style.container]" @keyup.enter="onConfirm">
<el-dialog title="重命名" :visible.sync="visible" width="30%">
  <el-form size="small" label-position="top" :rules="rules" :model="form" @submit.native.prevent="" ref="fm">
    <el-form-item prop="name">
      <el-input v-model="form.name" placeholder="不能包含 : / ? * “ < > | 等特殊字符" clearable ref="nameInput"></el-input>
    </el-form-item>
    <el-form-item>
      <el-checkbox v-model="showSuffix" @change="onSuffixChange">显示扩展名</el-checkbox>
    </el-form-item>
  </el-form>
  <span slot="footer">
    <el-button size="small" @click="onCancel" class="px-5">取 消</el-button>
    <el-button size="small" type="primary" @click="onConfirm" :loading="submitting" :disabled="disabled" class="px-5">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script lang="ts">

import { rename } from '@/api/doc'
import { Vue, Component, Prop, Emit, Ref } from 'vue-property-decorator'
import { textValidator } from '@/config/validator'

const splitName = (name = '') => {
  const idx = name.lastIndexOf('.')
  if (idx <= 0) return [name, '']
  return [name.slice(0, idx), name.slice(idx)]
}

@Component
export default class DocRenameModal extends Vue {
  @Ref() fm!: any

  visible = false

  data: any = null

  showSuffix = false

  suffix = ''

  resolve: ((value: any) => void) | null = null

  reject: (() => void) | null = null

  submitting = false

  form = {
    name: ''
  }

  rules = {
    name: [
      { required: true, message: '请输入文档名称' },
      { validator: textValidator }
    ]
  }

  get disabled () {
    return this.data?.name === this.form.name
  }

  onSuffixChange () {
    if (this.showSuffix) {
      this.form.name = this.form.name + this.suffix
    } else {
      this.form.name = splitName(this.form.name)[0]
    }
  }

  open (data: any) {
    this.data = data
    this.showSuffix = false
    this.suffix = ''
    this.visible = true
    this.$nextTick(() => {
      this.fm.resetFields()
      const fullName = data?.name || ''
      const [name, suffix] = splitName(fullName)
      this.form.name = name
      this.suffix = suffix
      const input = this.$refs.nameInput as any
      input.focus()
    })
    return new Promise((resolve, reject) => {
      this.resolve = resolve
      this.reject = reject
    })
  }

  onCancel () {
    this.visible = false
    if (this.reject) this.reject()
  }

  onConfirm () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      rename(this.data?.id, this.showSuffix ? this.form.name : (this.form.name + this.suffix)).then(() => {
        this.visible = false
        if (this.resolve) this.resolve(null)
      }).finally(() => {
        this.submitting = false
      })
    })
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

</style>
